package com.situation.util;

import com.auth0.jwt.JWT;
import com.auth0.jwt.JWTCreator;
import com.auth0.jwt.JWTVerifier;
import com.auth0.jwt.algorithms.Algorithm;
import com.auth0.jwt.exceptions.JWTDecodeException;
import com.auth0.jwt.exceptions.JWTVerificationException;
import com.auth0.jwt.interfaces.DecodedJWT;

import java.util.Date;
import java.util.HashMap;
import java.util.Map;

public class JWTUtil {

    private static final long expire = 3600 * 1000 * 100;
    private static final String securit = "!@#$%H*&^SxJ";

    /**
     * 生成token
     *
     * @param iss
     * @param sub
     * @param jti
     * @param claims
     * @return
     */
    public static String toToken(String iss, String sub, String jti, Map<String, String> claims) {
        JWTCreator.Builder builder = JWT.create();

        //设置头部
        Map<String, Object> headers = new HashMap<>();
        headers.put("alg", "HS256");
        headers.put("typ", "JWT");
        builder.withHeader(headers);

        //设置载荷
//        默认字段
        builder.withIssuer(iss);   //发行者
        builder.withSubject(sub);  //主题
        builder.withJWTId(jti);    //token唯一表示（使用sessionId）
        builder.withIssuedAt(new Date());  //发行时间
        builder.withExpiresAt(new Date(new Date().getTime() + expire));  //过期时间
//        自定义字段
        if (claims != null) {
            claims.forEach((k, v) -> {
                builder.withClaim(k, v);
            });
        }

        //签名，生成token
        return builder.sign(Algorithm.HMAC256(securit));
    }

    /**
     * 验签
     */
    public static boolean parseToken(String token) throws JWTVerificationException {
        if(token==null|| token.equals("")){
            return false;
        }
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(securit)).build();

        jwtVerifier.verify(token);
        return true;

    }

    /**
     * 解析数据
     */
    public static DecodedJWT parseData(String token) throws JWTDecodeException {
        JWTVerifier jwtVerifier = JWT.require(Algorithm.HMAC256(securit)).build();

        return jwtVerifier.verify(token);
    }
}
